/**
 * 新增事件
 */
var experss = require('express');
var router = experss.Router();
var db = require("../public/javascripts/db");
var multer = require('multer');
var upload = multer();
var _ = require("lodash");

/* GET home page. */
router.post('/',upload.array(), function(req, res, next) {
    let data = {
        isSuccess: false,
        data: null,
        msg: '新增事件失败！'
    };
    let equipmentid = _.trim(String(req.body.equipmentid));
    let type = _.trim(String(req.body.type));
    let finishDate = _.trim(String(req.body.finishDate));
    let depart = _.trim(String(req.body.depart));
    let departid = _.trim(String(req.body.departid));
    let workshop = _.trim(String(req.body.workshop));
    let workshopid = _.trim(String(req.body.workshopid));
    let desc = _.trim(String(req.body.desc));
    let recorderid = _.trim(String(req.body.recorderid)); // 事件初始：记录人为责任人， 移交后修改责任人

    let tableName = 'event_record';
    let colName = "`equipmentid`,`finishdate`,`recorddate`,`recorderid`,`maninchargeid`,`type`,`desc`, `depart`, `departid`,`workshop`,`workshopid`";
    let colValue = "'" + equipmentid + "','" + finishDate + "','" + new Date().toLocaleDateString()
     + "','"+ recorderid + "','" + recorderid + "','" + type + "','" + desc + "','" 
     + depart + "','" + departid + "','" + workshop + "','" + workshopid + "'";

    db.insert(tableName, colName, colValue, function(err, rows) {
        if(err) {
            return res.json(data);
        } else {
            console.log(rows.affectedRows)
            if(rows.affectedRows > 0) {
                if(equipmentid) {
                    db.changeState(equipmentid, '2', function(err, rows) {
                        if(err) {
                            // console.log("出错啦" + err)
                            return res.json(data);
                        } else {
                            // console.log("语法无误")
                            // console.log(rows.affectedRows)
                            if(rows.affectedRows > 0 ) {
                            // console.log("成功")
                                data.isSuccess = true;
                                data.msg = "新增事件成功！";
                                return res.json(data);
                            }
                        }
                    });
                } else {
                    data.isSuccess = true;
                    data.msg = "新增事件成功！";
                    return res.json(data);
                }
            } else {
                return res.json(data);
            }
        }
    })
})

module.exports = router;